package com.cqcvc.controller;

import com.cqcvc.pojo.User;
import com.cqcvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册
     * @param zh
     * @param mm
     * @param remm
     * @param name
     * @return
     */
    @RequestMapping("register")
    @ResponseBody
    public String register(String zh, String mm, String remm, String name){
        String msg="";
        if(mm.equals(remm)){
            userService.register(zh,mm,name);
            msg="<script>alert('Register Success!');location.href='login.jsp'</script>";
        }else{
            msg="<script>alert('Please Check your Password');location.href='reg.jsp'</script>";
        }
        return msg;
    }

    /**
     * 账号唯一性检测
     * @param zh
     * @return
     */
    @RequestMapping("checkUserAccount")
    @ResponseBody
    public String checkUserAccount(String zh){
        String msg="yes";
        List<User> list=userService.checkUserAccount(zh);
        if(list.size()>0){
            msg="no";
        }
        return msg;
    }

    @RequestMapping("login")
    public String login(User user, HttpSession session){

        User loginUser=userService.login(user.getZh(), user.getMm());
        if(loginUser!=null){
            //登录成功
            session.setAttribute("zh",loginUser.getZh());
            session.setAttribute("username",loginUser.getName());
            return "main.jsp";
        }else{
            return "login.jsp";
        }
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("zh");
        session.removeAttribute("username");
        session.invalidate();
        return "login.jsp";
    }

    @RequestMapping("editPwd")
    @ResponseBody
    public String editPwd(String mm,String newmm,String remm,HttpSession session){
        String msg="";
        if (newmm.equals(remm)){
            //允许修改
            String zh= (String) session.getAttribute("zh");
            userService.editPwd(zh,mm,newmm);
            msg="<script>alert('Change Password Success!');location.href='editPwd.jsp'</script>";
        }else {
            msg="<script>alert('Please Check your password!');location.href='editPwd.jsp'</script>";
        }
        return msg;
    }
}
